#include "game.h"
#include "tower.h"
#include "server.h"

#include <QDebug>

Tower::Tower(const qint32 ID)
   : Entity(ID)
{
   mBaseStats.type = ENTITY_TOWER;
   mTarget = 0;
   mNextAttackTime.setHMS(0,0,0);
}

void Tower::tick(const qreal timeDelta)
{
   if (mTarget)
   {
      // Time to fire at target?
      if (mGame->currentTime() >= mNextAttackTime)
      {
         // Face target
         QVector2D dir = mPosition - mTarget->position();

         qreal lastRotation = mRotation;
         mRotation = (atan2(dir.y(), dir.x()) * 180/M_PI);
         mUpdated = (mRotation != lastRotation);

         mGame->entityDoDamage(this, mTarget, 10);             // damage
         mNextAttackTime = mGame->currentTime().addMSecs(1000); // rate-of-fire
      }
   }
   //qDebug() << "Tower::tick: id=" << mID << "rot=" << mRotation << "updated=" << mUpdated << "timedelta=" << timeDelta;
}

void Tower::think()
{
   //qDebug()<< "Tower::think() id" << id();

   // Check for target change
   Entity *closest = mGame->entityManager.closest(position(), ENTITY_UNIT);

   int range = (20+mBaseStats.size*10);
   if (closest && ((closest->position() - position()).length()) <= range)
   {
      if (mTarget != closest)
      {
         mTarget = closest;
         //qDebug() << id() << " now targets" << mTarget->id();
      }
   }
   else if (mTarget)
   {
      // No target now
      mTarget = 0;
      mGame->server->sendEntityAttack(id(), 0, 0);
      //qDebug() << id() << "now has no target";
   }

   setNextThinkTime(mGame->currentTime().addMSecs(1000));
}
